package cat.joronya.supermanager.market;

import java.text.NumberFormat;
import java.util.Locale;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import android.widget.SimpleCursorAdapter.ViewBinder;
import android.widget.TextView;
import cat.joronya.supermanager.R;
import cat.joronya.supermanager.Supermanager;
import cat.joronya.supermanager.service.SupermanagerServiceHelper;
import cat.joronya.supermanager.utils.ImageDownloader;

public class MarketListActivity extends ListActivity 
{
	// pel Log
	private static final String TAG = "supermanager";
	
	private static final String POSITION_GUARDS = "GUARD";
	private static final String POSITION_FORWARDS = "FORWARD";
	private static final String POSITION_CENTERS = "CENTER";
	private static final String URL_PHOTO_PLAYER = 
		"http://www.acb.com/fotos_cara/jugadores/J%sLACB55.jpg";
	
	/**
     * The columns we are interested in from the database
     */
    private static final String[] PROJECTION = new String[] {
            Supermanager.Market._ID, 			// 0
            Supermanager.Market.ID_PLAYER,		// 1
            Supermanager.Market.STATUS,			// 2
            Supermanager.Market.NACIONALITY,	// 3
            Supermanager.Market.NAME, 			// 4
            Supermanager.Market.INFO,			// 5
            Supermanager.Market.TEAM,			// 6
            Supermanager.Market.BALANCE,		// 7
            Supermanager.Market.AVERAGE,		// 8
            Supermanager.Market.PRICE,			// 9
            Supermanager.Market.MODIFIED_DATE 	// 10
    };
    
    private Cursor cursor = null;
    
    private NumberFormat decform = null;
    private NumberFormat intform = null;
    
    @SuppressWarnings("unused")
	private String position = null;
    
    private final ImageDownloader imageDownloader = new ImageDownloader(this, Supermanager.PLAYERS);
    
	/** Called when the activity is first created. */
	@Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.market);
        
        // amaguem el ProgressBar
        ProgressBar progressBar = (ProgressBar) findViewById(R.id.market_loading);
        progressBar.setVisibility(View.INVISIBLE);
        
        // If no data was given in the intent, then use our default content provider.
        Intent intent = getIntent();
        Uri plUri = getIntent().getData();
        if( plUri == null) {
        	plUri = Supermanager.Market.CONTENT_URI;
            intent.setData(Supermanager.Market.CONTENT_URI);
        }
        
        if( decform == null )
        {
        	decform = NumberFormat.getNumberInstance(new Locale("es","ES"));
        	decform.setMinimumFractionDigits(2);
        }
        if( intform == null )
        {
        	intform = NumberFormat.getNumberInstance(new Locale("es","ES"));
        	intform.setGroupingUsed(true);
        }
        
        // inicialment mostrem ordenat per points
        showMarket(POSITION_GUARDS);
    }
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.market, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
    {
        // Handle item selection
        switch (item.getItemId()) 
        {
        	case R.id.guards:
        		showMarket(POSITION_GUARDS);
        		return true;
        	case R.id.forwards:
        		showMarket(POSITION_FORWARDS);
        		return true;
        	case R.id.centers:
        		showMarket(POSITION_CENTERS);
        		return true;
        	case R.id.refresh:
        		Log.d(TAG,"refreshing market player list");
				// mostrem el ProgressBar
		        ProgressBar progressBar = (ProgressBar) findViewById(R.id.market_loading);
		        progressBar.setVisibility(View.VISIBLE);
		        
				// cridar refresh al REST method
				SupermanagerServiceHelper.getInstance(this).getMarket(handler);
				return true;
        	default:
        		return super.onOptionsItemSelected(item);
        }
    }

    private void showMarket(String position)
    {
    	// guardem la posicio mostrada
        this.position = position;

		// canviem el titol del header per "Mercat: Bases" segons position
        TextView marketTextView = (TextView) findViewById(R.id.market_title);
        
        if( POSITION_GUARDS.equals(position) )
        	marketTextView.setText(getResources().getString(R.string.market_title,
        		getResources().getString(R.string.market_menu_guards)));
        else if( POSITION_FORWARDS.equals(position) )
        	marketTextView.setText(getResources().getString(R.string.market_title,
            		getResources().getString(R.string.market_menu_forwards)));
        else if( POSITION_CENTERS.equals(position) )
        	marketTextView.setText(getResources().getString(R.string.market_title,
            		getResources().getString(R.string.market_menu_centers)));

		// tenim cursor?
		if( cursor != null )
			stopManagingCursor(cursor);

		cursor = getContentResolver().query(getIntent().getData(), PROJECTION, 
       		Supermanager.Market.POSITION+"=?", 
       		new String[]{position},
            Supermanager.Market.DEFAULT_SORT_ORDER);
        
		startManagingCursor(cursor);

        // Used to map notes entries from the database to views
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, 
        		R.layout.market_row, 
        		cursor,
                new String[] { Supermanager.Market.NAME, 
        					   Supermanager.Market.BALANCE,
        					   Supermanager.Market.ID_PLAYER,
        					   Supermanager.Market.STATUS,
        					   Supermanager.Market.NACIONALITY,
        					   Supermanager.Market.TEAM,
        					   Supermanager.Market.AVERAGE,
        					   Supermanager.Market.PRICE}, 
        		new int[] { R.id.player_name,
        					R.id.balance,
        					R.id.avatar,
        					R.id.stick,
        					R.id.stick,
        					R.id.team,
        					R.id.average,
        					R.id.price});
        
        adapter.setViewBinder(new ViewBinder()
        {
        	public boolean setViewValue(View aView, Cursor aCursor, int aColumnIndex)
        	{
        		// ID_PLAYER
        		if( aColumnIndex == 1 )
        		{
        			String cod = aCursor.getString(aColumnIndex);
        			imageDownloader.download(String.format(URL_PHOTO_PLAYER, cod), (ImageView) aView);
        			return true;
        		}
        		// STATUS
        		else if( aColumnIndex == 2 )
        		{
        			// si te status, cal ficar stick corresponent
        			String status = aCursor.getString(aColumnIndex);
        			if( "lesio.png".equals(status) )
        			{
        				aView.setVisibility(View.VISIBLE);
        				ImageView statusView = (ImageView)aView;
        				statusView.setImageResource(R.drawable.lesio);
        				statusView.bringToFront();
        			}
        			else if( "semafor.png".equals(status) )
        			{
        				aView.setVisibility(View.VISIBLE);
        				ImageView statusView = (ImageView)aView;
        				// TODO: guardar drawable de semafor
        				statusView.setImageResource(R.drawable.lesio);        				
        				statusView.bringToFront();
        			}
        			else
        			{
        				aView.setVisibility(View.INVISIBLE);
        			}
        			return true;
        		}
        		// NACIONALITY
        		else if( aColumnIndex == 3 )
        		{
        			// si te nacionality, cal ficar stick corresponent
        			String nacionality = aCursor.getString(aColumnIndex);
        			if( "nacional.png".equals(nacionality) )
        			{
        				aView.setVisibility(View.VISIBLE);
        				ImageView statusView = (ImageView)aView;
        				statusView.setImageResource(R.drawable.nacional);
        				statusView.bringToFront();
        			}
        			else if( "extra.png".equals(nacionality) )
        			{
        				aView.setVisibility(View.VISIBLE);
        				ImageView statusView = (ImageView)aView;
        				statusView.setImageResource(R.drawable.extra);        				
        				statusView.bringToFront();
        			}
        			else
        			{
        				aView.setVisibility(View.INVISIBLE);
        			}
        			return true;
        		}
        		// AVERAGE
        		else if( aColumnIndex == 8 )
        		{
        			float average = aCursor.getFloat(aColumnIndex);
        			TextView textView = (TextView) aView;
        			textView.setText(decform.format(average));
        			return true;
        		}
        		// PRICE
        		else if( aColumnIndex == 9 )
        		{
        			int price = aCursor.getInt(aColumnIndex);
        			TextView textView = (TextView) aView;
        			textView.setText(intform.format(price));
        			return true;
        		}
        		else
        		{
        			return false;
        		}
        	}
        });
        
        setListAdapter(adapter);
	}
	
    public ImageDownloader getImageDownloader()
    {
        return imageDownloader;
    }
    
    private Handler handler = new Handler() 
    { 
        @Override 
        public void handleMessage(Message msg)
        { 
            //get data from msg 
        	int status = msg.getData().getInt(Supermanager.STATUS_MESSAGE);
            Log.d(TAG, "MarketListActivity received status: "+status);
            
            // TODO: check auth error, connectivity error, closed error, other error
            if( status == Supermanager.MARKET_PARSED_OK )
            {
            	// amaguem el ProgressBar
		        ProgressBar progressBar = (ProgressBar) findViewById(R.id.market_loading);
		        progressBar.setVisibility(View.INVISIBLE);
		        
		        
		        Toast.makeText(getApplicationContext(), 
            		R.string.market_toast_refresh_done, 
            		Toast.LENGTH_SHORT).show();
            }
            
            super.handleMessage(msg); 
        } 
    };

}
